//
//  SEGNavMenuListView.m
//  SEGUhomeStandard
//
//  Created by 揭婧雯 on 2019/2/28.
//  Copyright © 2019年 刘山. All rights reserved.
//

#import "SEGNavMenuListView.h"
#import "SEGRedDotManager.h"
@interface SEGNavMenuListView ()

/**
 背景
 */
@property (nonatomic, strong)UIImageView *bgView;

/**
 有红点的菜单个数
 */
@property (nonatomic, assign) NSUInteger redDotCount;

@end

@implementation SEGNavMenuListView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUpUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpUI];
    }
    return self;
}

- (void)setUpUI
{
    //背景图片
    UIImageView *bgView = [[UIImageView alloc] init];
    bgView.userInteractionEnabled = YES;
    [self addSubview:bgView];
    self.bgView = bgView;
}
- (void)setUpNavMenuListViewWithArray:(NSArray<NSArray<SEGMenuListModel *> *> *)dataSource finished:(SEGNavMenuListViewBlock)finished
//- (void)setUpNavMenuListViewWithArray:(NSArray <SEGMenuListModel *>*)menuListArray
{
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.superview);
    }];
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenView)]];

    //整理数据源为一维数组
    NSMutableArray *menuListArray = [NSMutableArray array];
    [dataSource enumerateObjectsUsingBlock:^(NSArray<SEGMenuListModel *> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
           [menuListArray addObject:model];
        }];
    }];

    //背景图片
    CGFloat arrowsHeight = 6.0 * kScaleWidth;//箭头高度
    CGFloat rowHeight = 44.0 * kScaleWidth;
    CGFloat imageWidth = 140 * kScaleWidth;
    CGFloat imageHeight = menuListArray.count * rowHeight + arrowsHeight;
    UIEdgeInsets insets = UIEdgeInsetsMake(10, 10, 10, 10);
    self.bgView.image = [[UIImage imageWithContentsOfFile:SEGPicName(@"pic_bg_list")] resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    [self.bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(42 + kStatusbarHeight);
        make.height.mas_equalTo(imageHeight);
        make.width.mas_equalTo(imageWidth);
        make.right.equalTo(self).offset(-6 * kScaleWidth);
    }];
    [self.bgView removeAllSubviews];//删除原来的菜单控件

    self.redDotCount = 0;

    //设置界面
    __weak typeof (self) weakSelf = self;
    [menuListArray enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        UIButton *itemButton =  [weakSelf createButtonWithModel:obj isShowLine:(idx != menuListArray.count - 1)];

        [itemButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.bgView).offset(rowHeight * idx + arrowsHeight);
            make.height.mas_equalTo(rowHeight);
            make.left.equalTo(weakSelf.bgView);
            make.right.equalTo(weakSelf.bgView);
        }];
    }];

    BOOL isRedDot = self.redDotCount > 0;
    finished(isRedDot);
}

- (UIButton *)createButtonWithModel:(SEGMenuListModel *)model isShowLine:(BOOL)isShowLine
{
    UIButton *itemButton = [[UIButton alloc] init];
    [itemButton setTitle:model.serviceName forState:UIControlStateNormal];
    [itemButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    itemButton.titleLabel.font = kFont_15;
    itemButton.titleEdgeInsets = UIEdgeInsetsMake(0, 48 * kScaleWidth, 0, 0);
    itemButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [itemButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        NSString *ids = model.settingsId;
        //点击之后修改红点状态
        NSArray *redDotsIds = [[SEGUhomeMediator sharedInstance] seg_getCurrentSettingIdsArray:@{}];
        if ([redDotsIds containsObject:ids]) {
            [[SEGUhomeMediator sharedInstance]seg_deleteRedDotWithId:@{@"idString":ids}];
        }
        UIView *redDot = [sender viewWithTag:5555];
        redDot.hidden = YES;
        
        //            self.redDotCount --;
        //            if (self.redDotCount == 0) {//没有红点
        //                finished(NO);
        //            }
        
        self.hidden = YES;
        [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithAction:[model yy_modelToJSONObject]];
    }];
    
    [itemButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithRed:39/255.0 green:39/255.0 blue:39/255.0 alpha:1.0]] forState:UIControlStateHighlighted];
    [self.bgView addSubview:itemButton];
    
    UIImageView *imgView = [[UIImageView alloc] init];

    BOOL isDark = NO;
    if (@available(iOS 12.0, *)) isDark = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark);
    
    UIImage *placeholderImage = [UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_70_70")];
    NSURL *iconUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,model.iosicon]];
    NSURL *iconDarkUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,[model darkIconWithIsDark:isDark]]];
    [imgView seg_setImageWithURL:iconUrl darkImageWithURL:iconDarkUrl placeholderImage:placeholderImage];
    
    [itemButton addSubview:imgView];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(itemButton);
        make.left.equalTo(itemButton).offset(20 * kScaleWidth);
        make.width.height.mas_equalTo(18 * kScaleWidth);
    }];
    
    if (isShowLine) {
        UIView *line2 = [[UIView alloc] init];
        line2.backgroundColor = [UIColor.whiteColor colorWithAlphaComponent:0.2f];
        [self.bgView addSubview:line2];
        [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.bgView).mas_offset(10 * kScaleWidth);
            make.right.equalTo(self.bgView).mas_offset(-10 * kScaleWidth);
            make.bottom.equalTo(itemButton);
            make.height.mas_equalTo(0.5);
        }];
    }
    
    NSArray *redDotsIds = [[SEGUhomeMediator sharedInstance] seg_getCurrentSettingIdsArray:@{}];
    if ([redDotsIds containsObject:model.settingsId]) {
        UIImageView *redImageView = [[UIImageView alloc] init];
        redImageView = [[UIImageView alloc]init];
        redImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"tab_red_round")];
        redImageView.contentMode = UIViewContentModeScaleAspectFill;
        redImageView.tag = 5555;
        [itemButton addSubview:redImageView];
        [redImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(itemButton).offset(14);
            make.left.equalTo(itemButton.titleLabel.mas_right).offset(1);
            make.width.height.mas_equalTo(8);
        }];
        self.redDotCount++;
    }
    
    return itemButton;
}

- (void)hiddenView
{
    self.hidden = YES;
}

@end
